<template>
  <div>
    <a-modal
      :visible.sync="visible"
      v-bind="$attrs"
      v-on="$listeners"
      :maskClosable="false"
      :footer="null"
      width="716px"
      :title="title"
      wrapClassName="video-modal-container"
      @cancel="closeModal()"
    >
      <div class="curve-modal-body">
        <a-row :gutter="0">
          <a-form-model ref="form" :model="form" :rules="formRules">
            <a-col :span="24">
              <a-form-model-item
                v-if="modelType != 'update' && !rootZhgdCode"
                label="请选择新增类型"
              >
                <a-radio-group v-model="resource" @change="groupChange">
                  <a-radio value="1"> 节点 </a-radio>
                  <a-radio value="2"> 视频 </a-radio>
                </a-radio-group>
              </a-form-model-item>
            </a-col>
            <div v-if="resource == 1">
              <a-col :span="24">
                <a-form-model-item label="序号" prop="sortNo">
                  <a-input
                    v-model="form.sortNo"
                    placeholder="请填写序号"
                    :maxLength="10"
                  >
                  </a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="节点名称" prop="nodeName">
                  <a-input
                    v-model="form.nodeName"
                    placeholder="请填写节点名称"
                    :maxLength="200"
                  >
                  </a-input>
                </a-form-model-item>
              </a-col>
            </div>
            <div v-if="resource == 2">
              <a-col :span="24">
                <a-form-model-item label="序号" prop="sortNo">
                  <a-input
                    v-model="form.sortNo"
                    placeholder="请填写序号"
                    :maxLength="10"
                  >
                  </a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="视频名称" prop="videoName">
                  <a-input
                    v-model="form.videoName"
                    placeholder="请填写视频名称"
                    :maxLength="200"
                  >
                  </a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="视频URL-高清" prop="hlsHd">
                  <a-input
                    v-model="form.hlsHd"
                    placeholder="请填写视频URL-高清"
                    :maxLength="500"
                  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="视频URL-流畅" prop="hls">
                  <a-input
                    v-model="form.hls"
                    placeholder="请填写视频URL-流畅"
                    :maxLength="500"
                  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="经纬度坐标" prop="lon">
                  <a-row :gutter="20">
                    <a-col :span="12">
                      <a-input
                        v-model="form.lon"
                        disabled
                        placeholder="请选择经纬度坐标"
                      ></a-input>
                    </a-col>
                    <a-col :span="12">
                      <a-input
                        v-model="form.lat"
                        disabled
                        placeholder="请选择经纬度坐标"
                      ></a-input>
                    </a-col>
                  </a-row>
                  <div class="map-container">
                    <div id="video-map"></div>
                    <div class="search-wrap">
                      <a-radio-group name="radioGroup" v-model="searchType">
                        <a-radio :value="1">按关键字搜索</a-radio>
                        <a-radio :value="2">按坐标搜索</a-radio>
                      </a-radio-group>
                      <div class="input-container">
                        <div class="input-body">
                          <a-input
                            v-if="searchType == 1"
                            placeholder="关键字搜索"
                            v-model="mapkey"
                          />
                          <template v-if="searchType == 2">
                            <a-input placeholder="请输入经度" v-model="lng" />
                            <div style="line-height: 30px">,</div>
                            <a-input placeholder="请输入纬度" v-model="lat" />
                          </template>
                        </div>
                        <div class="search" @click="search">
                          <a-icon
                            type="search"
                            :style="{
                              fontSize: '20px',
                              color: '#fff',
                            }"
                          />
                        </div>
                      </div>
                    </div>
                  </div>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="首页是否展示">
                  <a-radio-group v-model="form.status">
                    <a-radio value="1"> 是 </a-radio>
                    <a-radio value="0"> 否 </a-radio>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="设备序列号" prop="deviceSerialNumber">
                  <a-input
                    v-model="form.deviceSerialNumber"
                    placeholder="请填写设备序列号"
                    :maxLength="500"
                  >
                  </a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="通道号" prop="channelNumber">
                  <a-input
                    v-model="form.channelNumber"
                    placeholder="请填写通道号"
                    :maxLength="10"
                  >
                  </a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="AppKey" prop="appkey">
                  <a-input
                    v-model="form.appkey"
                    placeholder="请填写AppKey值"
                    :maxLength="500"
                  >
                  </a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="Secret" prop="secret">
                  <a-input
                    v-model="form.secret"
                    placeholder="请填写Secret值"
                    :maxLength="500"
                  >
                  </a-input>
                </a-form-model-item>
              </a-col>
              <div v-if="userFlag">
                <a-col :span="24">
                  <a-form-model-item label="是否调整角度">
                    <a-switch
                      :checked="form.ifAngleAdjustment"
                      @change="angleChange"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="24">
                  <a-form-model-item label="是否监测在线离线">
                    <a-switch default-checked v-model="form.ifMonitorOnline" />
                  </a-form-model-item>
                </a-col>
              </div>
              <div>
                <a-col :span="24" v-if="form.ifAngleAdjustment && userFlag">
                  <a-form-model-item label="类型" prop="type">
                    <a-radio-group v-model="form.type">
                      <a-radio value="0"> 球机 </a-radio>
                      <a-radio value="1"> 枪机 </a-radio>
                    </a-radio-group>
                  </a-form-model-item>
                </a-col>

                <a-col :span="24" v-if="form.ifAngleAdjustment && userFlag">
                  <a-form-model-item label="可操作群组" prop="configUserIds">
                    <a-select
                      mode="multiple"
                      style="width: 100%"
                      placeholder="请选择可操作群组"
                      @change="selectChange"
                      v-model="form.configUserIds"
                    >
                      <a-select-option
                        v-for="v in userRescource"
                        :key="v.id"
                        :value="v.id"
                      >
                        {{ v.groupName }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
              </div>
            </div>
          </a-form-model>
        </a-row>
      </div>
      <div class="modal-footer" v-if="resource">
        <a-button @click="closeModal"> 取 消</a-button>
        <a-button type="primary" @click="confirm"> 确 定 </a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
import bjSelect from "@/components/bj-select";
import {
  getZhgdVideoNodeAdd,
  getZhgdVideoNodeDetail,
  getZhgdVideoAdd,
  getZhgdVideoDetail,
  superUserFlag,
  getVideoUserList,
} from "@/api/wisdom-beam/security-app.js";
import { notificationTip, getFindLonLat } from "@/utils";
import { mapGetters } from "vuex";
let mapInstance = null;
export default {
  components: {
    bjSelect,
  },
  props: [
    "visible",
    "modelType",
    "rootZhgdCode",
    "parentId",
    "editResource",
    "zhgdDeptCode",
  ],
  watch: {
    visible: {
      handler(val) {
        this.$emit("update:visible", val);
        if (val) {
          this.getInit();
          this.superUserFlag();
        }
      },
      immediate: true,
    },
  },
  computed: {
    ...mapGetters(["organization", "projectSource"]),
  },
  data() {
    return {
      childId: "",
      resource: "",
      searchType: 1,
      lng: "",
      lat: "",
      form: {
        //在线离线
        ifMonitorOnline: true,
        //排序
        sortNo: "",
        //节点名称
        nodeName: "",
        //视频名称
        videoName: "",
        //hls地址_高清
        hlsHd: "",
        //h5地址_高清
        hls: "",
        //经度
        lon: "",
        //纬度
        lat: "",
        //1推荐首页 0不推荐
        status: "1",
        //1是角度调整，0不是角度调整
        ifAngleAdjustment: false,
        //类型
        type: "",
        //设备序列号
        deviceSerialNumber: "",
        //通道号
        channelNumber: "",
        //appKey
        appkey: "3af0a5704b2e415c8a49decc5c58d4d5",
        //secret
        secret: "6b01b48a27203f9a031d622f4fdd5674",
        configUserIds: [],
      },
      formRules: {
        sortNo: [
          {
            required: true,
            message: "请填写序号",
          },
          {
            pattern: /^[0-9]*$/,
            message: "请输入正整数",
          },
        ],
        nodeName: [
          {
            required: true,
            message: "请填写节点名称",
          },
        ],
        videoName: [
          {
            required: true,
            message: "请填写视频名称",
          },
        ],
        hlsHd: [
          {
            required: true,
            message: "请填写hls地址",
          },
        ],
        hls: [
          {
            required: true,
            message: "请填写h5地址",
          },
        ],
        lon: [
          {
            required: true,
            message: "请选择经纬度坐标",
          },
        ],
        deviceSerialNumber: [
          {
            required: true,
            message: "请填写设备序列号",
          },
        ],
        channelNumber: [
          {
            required: true,
            message: "请填写通道号",
          },
        ],
        appkey: [
          {
            required: true,
            message: "请填写AppKey值",
          },
        ],
        secret: [
          {
            required: true,
            message: "请填写Secret值",
          },
        ],
        configUserIds: [
          {
            required: true,
            message: "请填写可操作群组",
          },
        ],
        type: [
          {
            required: true,
            message: "请选择类型",
          },
        ],
      },
      title: "",
      mapkey: "",
      //默认经纬度
      defaultCenter: {},

      userRescource: [],
      userReplaceFields: { key: "id", label: "groupName" },
      userLoading: false,

      userFlag: false,
    };
  },
  methods: {
    // 可操作群组切换
    selectChange(value) {},
    //查询人员列表
    getUserList() {
      return new Promise((resolve, reject) => {
        this.userLoading = true;
        getVideoUserList()
          .then((res) => {
            let { data } = res;
            this.userRescource = data?.result || [];
            resolve();
          })
          .catch((_) => {
            reject();
            this.userRescource = [];
          })
          .finally((_) => {
            this.userLoading = false;
          });
      });
    },
    //查询人员列表
    superUserFlag() {
      superUserFlag()
        .then((res) => {
          this.userFlag = res.data.result;
        })
        .catch((_) => {});
    },
    //初始化表单
    getInit() {
      if (this.modelType == "node") {
        this.title = "新增根节点";
        this.resource = 1;
      }
      if (this.modelType == "save") {
        this.title = "新增";
        this.getUserList();
      }
      if (this.modelType == "update") {
        this.resource = this.editResource;
        if (this.resource == "1") {
          this.title = "编辑节点";
          this.getNodeDetail();
        }
        if (this.resource == "2") {
          this.title = "编辑视频";
          this.getVideoDetail();
          this.getUserList();
        }
      }
    },
    //查询节点详情
    getNodeDetail() {
      getZhgdVideoNodeDetail(this.parentId)
        .then((res) => {
          this.form = res?.data?.result || {};
        })
        .catch((_) => {
          this.form = {};
        });
    },
    //查询视频详情
    getVideoDetail() {
      getZhgdVideoDetail(this.parentId)
        .then((res) => {
          let source = res?.data?.result || {};
          source.ifMonitorOnline = source.ifMonitorOnline == 1 ? true : false;
          this.form = source;
          let zhgdVideoUserList = this.form?.zhgdVideoUserList || [];
          this.form.configUserIds = zhgdVideoUserList.map((v) => v.userGroupId);

          if (this.form.ifAngleAdjustment == 1) {
            this.form.ifAngleAdjustment = true;
          } else {
            this.form.ifAngleAdjustment = false;
          }

          this.$nextTick(() => {
            this.initMap(this.form?.lon, this.form?.lat);
          });
        })
        .catch((_) => {
          this.form = {};
        });
    },
    //关闭弹框
    closeModal() {
      this.resource = "";
      this.mapkey = "";
      this.$refs.form.resetFields();
      this.resetForm();
      this.$emit("update:visible", false);
    },
    //确定
    confirm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          let { form, parentId, rootZhgdCode } = this;
          if (this.title == "新增根节点") {
            let jsonForm = {
              //父节点 第一个节点为0
              parentId: 0,
              //标段编码 第一节点必填
              zhgdDeptCode: rootZhgdCode,
              //节点类型 第一节点必填 1萤石云；2安防
              type: "1",
              //排序
              sortNo: form.sortNo,
              //节点名称
              nodeName: form.nodeName,
            };
            getZhgdVideoNodeAdd(jsonForm)
              .then((res) => {
                this.$parent.getNodeTreeList();
                this.closeModal();
                notificationTip("success", "新增根节点成功！");
              })
              .catch();
          }
          if (this.title == "新增子节点") {
            let jsonForm = {
              parentId: parentId,
              zhgdDeptCode: "",
              type: "",
              sortNo: form.sortNo,
              nodeName: form.nodeName,
            };
            getZhgdVideoNodeAdd(jsonForm)
              .then((res) => {
                this.$parent.getNodeTreeList();
                this.closeModal();
                notificationTip("success", "新增子节点成功！");
              })
              .catch();
          }
          if (this.title == "新增视频") {
            let jsonForm = {
              ifMonitorOnline: this.form.ifMonitorOnline ? 1 : 0,
              //排序
              sortNo: form.sortNo,
              //节点id
              nodeId: parentId,
              //视频名称
              videoName: form.videoName,
              //hls地址_高清
              hlsHd: form.hlsHd,
              //hls地址_标清
              h5: "",
              //hls地址_流畅
              hls: form.hls,
              //经度
              lon: form.lon,
              //纬度
              lat: form.lat,
              //1推荐首页 0不推荐
              status: form.status,
              //1是角度调整，0不是角度调整
              ifAngleAdjustment: form.ifAngleAdjustment ? 1 : 0,
              //0球机 1枪机
              type: form.type,
              //设备序列号
              deviceSerialNumber: form.deviceSerialNumber,
              //通道号
              channelNumber: form.channelNumber,
              //key值
              appkey: form.appkey,
              //secret值
              secret: form.secret,
              //可操作群组
              configUserIds: form.configUserIds
                ? form.configUserIds.toString()
                : "",
            };
            getZhgdVideoAdd(jsonForm)
              .then((res) => {
                this.$parent.getNodeTreeList();
                this.closeModal();
                notificationTip("success", "新增视频成功！");
              })
              .catch();
          }
          if (this.title == "编辑节点") {
            let jsonForm = {
              id: form.id,
              parentId: form.parentId,
              zhgdDeptCode: form.zhgdDeptCode,
              type: form.type,
              sortNo: form.sortNo,
              nodeName: form.nodeName,
            };
            getZhgdVideoNodeAdd(jsonForm)
              .then((res) => {
                this.$parent.getNodeTreeList();
                this.closeModal();
                notificationTip("success", "编辑节点成功！");
              })
              .catch((_) => {});
          }
          if (this.title == "编辑视频") {
            let jsonForm = {
              //排序
              ifMonitorOnline: this.form.ifMonitorOnline ? 1 : 0,
              sortNo: form.sortNo,
              id: form.id,
              nodeId: form.nodeId,
              videoName: form.videoName,
              hlsHd: form.hlsHd,
              h5: form.h5,
              hls: form.hls,
              lon: form.lon,
              lat: form.lat,
              status: form.status,
              ifAngleAdjustment: form.ifAngleAdjustment ? 1 : 0,
              type: form.type,
              deviceSerialNumber: form.deviceSerialNumber,
              channelNumber: form.channelNumber,
              appkey: form.appkey,
              secret: form.secret,
              //可操作群组
              configUserIds: form.configUserIds
                ? form.configUserIds.toString()
                : "",
            };
            getZhgdVideoAdd(jsonForm)
              .then((res) => {
                this.$parent.getNodeTreeList();
                this.closeModal();
                notificationTip("success", "编辑视频成功！");
              })
              .catch((_) => {});
          }
        }
      });
    },
    //是否角度调整
    angleChange(checked) {
      this.form.ifAngleAdjustment = checked;
      if (!checked) {
        this.form.type = "";
        this.form.configUserIds = [];
      }
    },
    //节点 视频
    groupChange(e) {
      let findIndex = e.target.value;
      this.$refs.form.resetFields();
      this.resetForm();
      if (findIndex == 1) {
        this.title = "新增子节点";
      }
      if (findIndex == 2) {
        this.title = "新增视频";
        this.$nextTick(() => {
          this.initMap();
        });
      }
    },
    search() {
      var that = this;
      if (this.searchType == 2) {
        if (!this.lng || !this.lat) return;
        this.addMapMarker(new AMap.LngLat(this.lng, this.lat));
        mapInstance.setCenter([this.lng, this.lat]);
        that.form.lon = this.lng;
        that.form.lat = this.lat;
        return;
      }
      if (!this.mapkey) return;
      mapInstance.plugin(["AMap.PlaceSearch"], function () {
        var placeSearch = new AMap.PlaceSearch({
          city: "全国",
          citylimit: true,
          autoFitView: true,
        });
        placeSearch.search(that.mapkey, async function (status, result) {
          if (status == "complete") {
            if (result.poiList.pois.length == 0) {
              return;
            }
            that.addMapMarker(result.poiList.pois[0].location);
            that.form.lon = result.poiList.pois[0].location.lng;
            that.form.lat = result.poiList.pois[0].location.lat;
          }
          mapInstance.setFitView();
        });
      });
    },
    //新增弹窗-地图加载
    initMap(lng, lat) {
      this.defaultCenter = getFindLonLat(
        this.organization,
        this.projectSource
      ) || { geox: 118.8, geoy: 32.06 };
      let { geox, geoy } = this.defaultCenter;
      mapInstance = new AMap.Map("video-map", {
        zoom: 15,
        center: [lng ? lng : geox, lat ? lat : geoy],
      });
      if (lng && lat) {
        this.addMapMarker(new AMap.LngLat(lng, lat));
      }
      mapInstance.on("click", async (e) => {
        this.form.lon = e.lnglat.lng; //经度
        this.form.lat = e.lnglat.lat; //纬度
        this.addMapMarker(e.lnglat);
      });
    },
    //添加自定义点标记
    addMapMarker(LngLat) {
      if (this.marker) {
        mapInstance.remove(this.marker);
      }
      this.marker = new AMap.Marker({
        position: LngLat,
      });
      mapInstance.add(this.marker);
    },
    //重置表单
    resetForm() {
      this.lng = "";
      this.lat = "";
      this.mapkey = "";
      this.form = {
        ifMonitorOnline: true,
        //排序
        sortNo: "",
        //节点名称
        nodeName: "",
        //视频名称
        videoName: "",
        //hls地址_高清
        hlsHd: "",
        //h5地址_高清
        hls: "",
        //经度
        lon: "",
        //纬度
        lat: "",
        //1推荐首页 0不推荐
        status: "1",
        //1是角度调整，0不是角度调整
        ifAngleAdjustment: false,
        //类型
        type: "",
        //设备序列号
        deviceSerialNumber: "",
        //通道号
        channelNumber: "",
        //appKey
        appkey: "3af0a5704b2e415c8a49decc5c58d4d5",
        //secret
        secret: "6b01b48a27203f9a031d622f4fdd5674",
        configUserIds: [],
      };
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.video-modal-container {
  .ant-modal-body {
    padding: 0;
  }
  .curve-modal-body {
    padding: 20px 70px 20px 20px;
    max-height: 600px;
    .custom-scrollbar();
  }
  .modal-footer {
    box-sizing: border-box;
    border-top: 1px solid #e8e8e8;
    padding: 20px 0;
    text-align: center;
    button {
      &:last-child {
        margin-left: 20px;
      }
    }
  }
  .map-container {
    width: 100%;
    height: 340px;
    position: relative;
    .box-sizing();
    border: 2px solid #fff;
    border-radius: 4px;
    .search-wrap {
      width: 351px;
      position: absolute;
      left: 10px;
      top: 10px;
      right: 10px;
      background: #ffffff;
      box-shadow: 0px 2px 3px 0px rgba(93, 93, 93, 0.34);
      border-radius: 4px;
      padding: 0 16px 12px;
    }
    .input-container {
      width: 100%;
      height: 30px;
      border-radius: 4px;
      overflow: hidden;
      background: #ffffff;

      .flex();
      .input-body {
        flex: 1;
        border: 1px solid #d4d7d8;
        border-radius: 4px 0px 0px 4px;
        .flex();
      }
      .ant-input {
        flex: 1;
        height: 28px;
        border-radius: 0;
        border: 0;
        margin: 0;
      }
      .ant-input:focus {
        box-shadow: 0 0 0;
      }
      .search {
        width: 60px;
        height: 30px;
        background: rgb(49, 131, 255);
        border: 1px solid rgb(49, 131, 255);
        border-radius: 0px 4px 4px 0px;
        text-align: center;
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
    #video-map {
      height: 100%;
      width: 100%;
    }
  }
  .ant-form-item {
    display: flex;
    .ant-form-item-label {
      width: 140px;
      white-space: pre-wrap;
      display: flex;
      justify-content: flex-end;
      line-height: 20px;
      align-items: center;
      margin-right: 15px;
      height: 36px;
      label {
        color: #999999;
      }
    }
    .check-item-select {
      height: 86px;
      .ant-select-selection__rendered {
        height: 86px;
        .ant-select-selection__placeholder {
          margin-top: -40px !important;
        }
      }
    }
    .ant-form-item-control-wrapper {
      flex: 1;
    }
  }
}
</style>
